<template>
  <div class="common-layout">
    <div class="login-container">
      <h2>登录界面</h2>
      <form @submit.prevent="handleLoginClick">
        <!-- 表单内容保持不变 -->
        <div class="form-group">
          <label for="user_name">用户名</label>
          <input v-model="loginObj.user_name" type="text" id="user_name" required />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input v-model="loginObj.password" type="password" id="password" required />
        </div>
        <div class="form-group">
          <label for="captcha">验证码</label>
          <input v-model="captcha" type="text" id="captcha" required />
          <img :src="captchaImage" alt="验证码" @click="refreshCaptcha" />
        </div>
        <div class="form-group">
          <el-checkbox v-model="loginObj.rememberMe" label="记住密码" size="large">记住密码</el-checkbox>
        </div>
        <button type="submit">登录</button>
        <div v-if="errorMessage" class="error">{{ errorMessage }}</div>
        <vcode :show="isShow" @success="success" @close="close" @fail="fail" :imgs="[Img]"></vcode>
      </form>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import vcode from 'vue3-puzzle-vcode';
const Img = ref('/images/17.jpg');
import { ElMessage } from 'element-plus';
import api from '../api';
const router = useRouter();
const captchaImage = ref('/api/captcha');
const errorMessage = ref('');
const isShow = ref(false);

const loginObj = ref({
  user_name: '',
  password: '',
  rememberMe: false,
});
const captcha = ref('');

const refreshCaptcha = () => {
  captchaImage.value = `/api/captcha?t=${new Date().getTime()}`;
};

onMounted(() => {
  const savedLogin = JSON.parse(localStorage.getItem('loginForm'));
  console.log('加载保存的登录信息:', savedLogin); // 调试信息
  if (savedLogin && savedLogin.rememberMe) {
    loginObj.value.user_name = savedLogin.user_name;
    loginObj.value.password = savedLogin.password;
    loginObj.value.rememberMe = savedLogin.rememberMe;
  }
  
});

const success = async () => {
  isShow.value = false;
  await handleLogin();
};

const fail = () => {
  ElMessage({
    type: 'warning',
    message: '滑块验证失败，请重试',
  });
};

const handleLogin = async () => {
  if (!loginObj.value.user_name || !loginObj.value.password || !captcha.value) {
    errorMessage.value = '所有字段不能为空';
    return;
  }

  try {
    const response = await axios.post('/api/login', {
      user_name: loginObj.value.user_name,
      password: loginObj.value.password,
    }, {
      params: { captcha: captcha.value }
    });

    if (response.data && response.data.code === 200) {
      localStorage.setItem('token', response.data.data);

      console.log('保存登录信息:', loginObj.value); // 调试信息

      if (loginObj.value.rememberMe) {
        localStorage.setItem('loginForm', JSON.stringify(loginObj.value));
      } else {
        localStorage.removeItem('loginForm');
      }
      console.log(loginObj.value.user_name);
      const result = await api.getForm('/api/user/getusername',loginObj.value);
      console.log(result.data);
      if(result.data.role_id==0){
        router.push('/goodsstaff')
      }else if(result.data.role_id==1){
        router.push('/goods');
      }
      //         router.push('/goods')
        // .then(() => console.log('跳转到goods成功'))
        // .catch((err) => console.error('跳转失败:', err));
    } else if (response.data.code === 401) {
      errorMessage.value = '验证码错误';
      refreshCaptcha();
    } else if (response.data.code === 403) {
      errorMessage.value = '用户名或密码错误';
    } else {
      errorMessage.value = '登录失败，请重试';
    }
  } catch (error) {
    console.error('登录请求失败:', error);
    errorMessage.value = '登录请求失败';
  }
};

const handleLoginClick = () => {
  isShow.value = true;
};
refreshCaptcha();
</script>


<style scoped>
.form-group img {
  cursor: pointer;
  margin-top: 10px;
  width: 130px;
  height: 48px;
  border: 1px solid #ddd;
}

.login-container {
  max-width: 400px;
  margin: 100px auto;
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  font-family: 'Arial', sans-serif;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #666;
}

.form-group input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  box-sizing: border-box;
  background-color: #f9f9f9;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  border-color: #42b983;
  outline: none;
}

button {
  width: 100%;
  padding: 12px;
  background: linear-gradient(to right, #42b983, #38a169);
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 18px;
  cursor: pointer;
  transition: background 0.3s ease;
}

button:hover {
  background: linear-gradient(to right, #38a169, #42b983);
}

.error {
  color: red;
  margin-top: 15px;
  text-align: center;
  font-weight: bold;
}
</style>